package com.trt.interceptor;

import com.trt.utils.JsonResult;
import com.trt.utils.JsonUtils;
import com.trt.utils.RedisOperator;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @author tanrentao
 * @date 2021-08-11
 * @desc 分布式会话拦截器
 */
public class UserTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisOperator redisOperator;

    public static final String REDIS_USER_TOKEN = "redis_user_token";


    /**
     * 拦截请求，在访问controller调用之前
     * @param request
     * @param response
     * @param handler 
     * @return boolean
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // System.out.println("进入到拦截器，被拦截。。。");

        String userId = request.getHeader("headerUserId");
        String userToken = request.getHeader("headerUserToken");

        if (StringUtils.isNotBlank(userToken) && StringUtils.isNotBlank(userToken)) {
            String uniqueToken = redisOperator.get(REDIS_USER_TOKEN + ":" + userId);
            if (StringUtils.isNotBlank(uniqueToken)) {
                // System.out.println("请登录...");
                returnErrorResponse(response, JsonResult.errorMsg("请登录..."));
                return false;
            } else {
                if (uniqueToken.equals(userToken)) {
                    // System.out.println("账号在异地登录...");
                    returnErrorResponse(response, JsonResult.errorMsg("账号在异地登录..."));
                    return false;
                }
            }
        } else {
            // System.out.println("请登录...");
            returnErrorResponse(response, JsonResult.errorMsg("请登录..."));
            return false;
        }

        /**
         * false:请求被拦截，被驳回，验证出现问题
         * true:请求在经过验证校验以后，是0K的，是可以放行的
         */
        return true;
    }

    public void returnErrorResponse(HttpServletResponse response, JsonResult result) {
        OutputStream out = null;
       try {
           response.setCharacterEncoding("utf-8");
           response.setContentType("text/json");
           out.write(JsonUtils.objectToJson(result).getBytes("utf-8"));
           out.flush();
       } catch (IOException e) {
           e.printStackTrace();
       } finally {
           try {
               if (out != null) {
                   out.close();
               }
           } catch (IOException e) {
               e.printStackTrace();
           }
       }
    }

    /**
     * 
     * 请求访问controller之后，渲染视图之前
     * @param request
     * @param response
     * @param handler
     * @param modelAndView 
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 
     * 请求访问controller之后，渲染视图之后
     * @param request
     * @param response
     * @param handler
     * @param ex 
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
